import fs from 'fs';
import path from 'path';
export default function copyResource(options = {}) {
  const { targets = [] } = options;
  return {
    name: 'copy-resource',
    generateBundle() {
      for (const target of targets) {
        const absSrc = path.resolve(target.src);

        if (!fs.existsSync(absSrc)) {
          this.warn(`[emit-assets] File or folder not found: ${absSrc}`);
          continue;
        }

        const stat = fs.statSync(absSrc);
        const baseDir = stat.isDirectory() ? absSrc : path.dirname(absSrc);

        copyRecursiveWithEmit(absSrc, baseDir, this.emitFile.bind(this), target.dest);
      }
    }
  };
}


/**
 * 递归读取文件并通过 emitFile 注入到 Rollup 构建流程中
 * @param {string} src - 原始源路径
 * @param {string} baseDir - 用于保持目录结构
 * @param {function} emit - this.emitFile
 * @param {string} targetPrefix - 输出前缀，如 'assets'
 */
function copyRecursiveWithEmit(src, baseDir, emit, targetPrefix) {
  const stat = fs.statSync(src);

  if (stat.isDirectory()) {
    const entries = fs.readdirSync(src);
    for (const entry of entries) {
      const entryPath = path.join(src, entry);
      copyRecursiveWithEmit(entryPath, baseDir, emit, targetPrefix);
    }
  } else {
    const relativePath = path.relative(baseDir, src).replace(/\\/g, '/'); // 相对路径
    const fileName = `${targetPrefix}/${relativePath}`;
    const content = fs.readFileSync(src);
    emit({
      type: 'asset',
      fileName,
      source: content
    });
  }
}